﻿using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Simple.Tools;
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;

namespace SimpleSaas.Web.Common
/// <summary>
/// 版 本 钢易智企2.0 V 2.0.0 钢易智企2.0
/// Copyright (c) 2023 杭州钢易科技有限公司
/// 创建人：曾东明
/// 日 期：2024
/// 描 述：
/// </summary>
{
	public class SimpleExceptionAttributer : ExceptionFilterAttribute
	{
		private ILogger<SimpleExceptionAttributer> logger;
		private IModelMetadataProvider modelMetadataProvider;

		[Autowired]
		protected IWebHostEnvironment environment { get; set; }

		public SimpleExceptionAttributer(ILogger<SimpleExceptionAttributer> logger, IModelMetadataProvider modelMetadataProvider, IWebHostEnvironment environment)
		{
			this.logger = logger;
			this.modelMetadataProvider = modelMetadataProvider;
			this.environment = environment;

		}
		public override void OnException(ExceptionContext context)
		{
			StringBuilder messageInfomations = new StringBuilder();

			string msg = string.Empty;
			GetErrorMeesage(context.Exception, messageInfomations);

			if (environment.IsDevelopment())
			{
				msg = messageInfomations.ToString();
			}
			else
			{
				msg = "服务器异常,请联系管理员!";
			}
			logger.LogError(messageInfomations.ToString());
			if (!context.ExceptionHandled)
			{
				context.Result = new JsonResult(new SimpleSaas.Common.BaseMessage(msg, 500));
			}
			base.OnException(context);
		}
		private void GetErrorMeesage(Exception ex, StringBuilder message)
		{
			if (SimpleCheck.IsNotNull(ex))
			{
				message.Append("message\t:\t" + ex.Message);
				message.Append("stackTrace\t:\t" + ex.StackTrace);
				if (SimpleCheck.IsNotNull(ex.InnerException))
				{
					GetErrorMeesage(ex.InnerException, message);
				}
			}
		}
	}
}
